import React from 'react';
import style from './style.scss';
import _ from 'lodash';
import Icon from 'antd/lib/icon';
import Menu from 'antd/lib/menu';
import Alert from 'antd/lib/alert';
import Input from 'antd/lib/input';
import Button from 'antd/lib/button';
import Form from 'antd/lib/form';
import MonacoEditor from 'react-monaco-editor';
const FormItem = Form.Item;
import Notification from 'antd/lib/notification';


const { TextArea } = Input;
export default class EditModule extends  React.Component {
  state={
    loading: false,
    style: this.props.templateID < 4 ? 0 : 1,
    dataValue: ''
  }
  componentDidMount(){
    let {module} = this.props
    this.props.getModuleDetail({
      hosId:this.props.HospitalId,
      pageId:module.id,
      style: this.state.style
    })
    this.props.getModuleData({
      hosId:this.props.HospitalId,
      page:module.id,
      style: this.state.style
    })
  }
  componentWillReceiveProps(nextProps){
    if(parseInt(this.props.module.id ) !==  parseInt(nextProps.module.id)){
      console.log('更新module id')
      let {module} = nextProps
      this.props.getModuleDetail({
        hosId:this.props.HospitalId,
        pageId:module.id,
        style: this.state.style
      })
      this.props.getModuleData({
        hosId:this.props.HospitalId,
        page:module.id,
        style: this.state.style
      })
    }
  }
  onDataChange (newValue, e, m) {
    try {
      const value = JSON.parse(newValue)
      this.setState({error: false}, v => {
        this.props.saveDataArea(value)
        this.props.templateModifyTrue()
      })
    } catch (err) {
      this.setState({error: true}, v => {
        this.props.saveDataArea(newValue)
        this.props.templateModifyTrue()
        Notification.error({
          message: '数据结构有误,请确认'
        });
      })
    }
  }
  updateTextarea(e){
    let value = e.target.value
    this.props.saveTextArea(value)
  }
  syncTextArea(){
    this.setState({loading: true})
    let {module} = this.props
    if (!this.props.moduleDetail.txtData) {
      return
    }
    let result = this.props.syncTextArea({
      hosId:this.props.HospitalId,
      pageId:module.id,
      sections:this.props.moduleDetail.txtData
    })

    result.then((res)=>{
      if(res.payload){
        this.setState({loading: false});
        this.props.templateModifyFalse();
        Notification.success({
          message: '同步模块文字成功！'
        });
      }else{
        this.setState({loading: false});
        Notification.error({
          message: '同步失败！',
          description: '服务当前不可用'
        });
      }
    })

  }
  syncDataArea(){
    if(this.state.error) {
      Notification.error({
        message: '数据结构有误,请确认'
      });
      return false
    }
    let {module} = this.props
    const chartData = this.state.style === 1 ? this.props.moduleData : this.props.moduleData.chartData
    const chartOldData = this.state.style ===1 ?  this.props.moduleOldData : this.props.moduleOldData.chartData
    this.state.formatError = false
    if (chartOldData instanceof Array) {
      if (!chartData instanceof Array) {
        Notification.error({
          message: '数据格式应该是数组'
        });
        return false
      }
      else {
        chartOldData.forEach((v, index) => {
          if (v.constructor === Object) {
            console.log(Object.keys(v).join() === Object.keys(chartData[index]).join())
            if (!(Object.keys(v).join() === Object.keys(chartData[index]).join())) {
              this.state.formatError = true
              Notification.error({
                message: '新数据的key值与原数据key值不符'
              });
              return false
            }
          }
        })
      }
    }
    if (chartOldData && chartOldData.constructor === Object) {
      if (!(chartData.constructor === Object)) {
        Notification.error({
          message: '数据格式应该是Object'
        });
        return false
      }
      else {
        if (!(Object.keys(chartOldData).join() === Object.keys(chartData).join())) {
          this.state.formatError = true
          Notification.error({
            message: '新数据的key值与原数据key值不符'
          });
          return false
        }
      }
    }
    if (this.state.formatError) {
      return false
    }
    this.setState({loading: true})
    const chart = JSON.stringify(chartData)
    let result = this.props.syncDataArea({
      hosId:this.props.HospitalId,
      page:module.id,
      style: this.state.style,
      chart: chart
    })

    result.then((res)=>{
      if(res.payload){
        let {module} = this.props
        this.setState({loading: false});
        this.props.templateModifyFalse();
        Notification.success({
          message: '同步模块数据成功！'
        });
        this.props.checkChart()
        this.props.getModuleData({
          hosId:this.props.HospitalId,
          page:module.id,
          style: this.state.style
        })
      }else{
        this.setState({loading: false});
        Notification.error({
          message: '同步失败！',
          description: '服务当前不可用'
        });
      }
    })

  }
  render(){
    let txtData = this.props.moduleDetail ? this.props.moduleDetail.txtData : "这个模块还没有文本数据！"
    let pageNum = this.props.moduleDetail ? this.props.moduleDetail.pageNum : ""
    let chapterNum = this.props.moduleDetail ? this.props.moduleDetail.chapterNum : ""
    const moduleData = this.props.moduleData ? this.props.moduleData : {}
    let code
    let isShowCode
    if (parseInt(this.props.templateID) === 4) {
      isShowCode = true
      code= moduleData ? (moduleData.constructor === String ? moduleData : JSON.stringify(moduleData, null, 2)) : JSON.stringify({})
    } else {
      isShowCode = moduleData.chartData ? true : false
      code= moduleData.chartData ? (moduleData.chartData.constructor === String ? moduleData.chartData : JSON.stringify(moduleData.chartData, null, 2)) : JSON.stringify({})
    }
    const options = {
      disableLayerHinting: true,
      disableMonospaceOptimizations: true
    }
    return <div>
      <Alert message={`当前编辑的模块名是${this.props.module.name}，页码为${pageNum},章节码为${chapterNum}`} type="info" showIcon />
      <Menu
        mode="horizontal"
        selectedKeys={["edit"]}
      >
        <Menu.Item key="edit">
          <Icon type="mail" />编辑模块
        </Menu.Item>
        <Menu.Item key="preview">
          <a href={this.props.templateID==4? `http://121.42.252.26:3000/horizontal/${this.props.HospitalId}?template=${this.props.templateID}&style=1&module=${parseInt(this.props.module.id)}` : `http://121.42.252.26:3000/${this.props.HospitalId}?template=${this.props.templateID}&style=0&module=${parseInt(this.props.module.id)}`} target="_blank" ><Icon type="mail" />预览当前模块web版本</a>
        </Menu.Item>

      </Menu>

      <div className={style.edit_body}>

        {isShowCode ? <div>
          <div className={style.text_title}>编辑模块数据</div>
          <div className={style.text_left}>
            <MonacoEditor
              width="800"
              height="400"
              language="json"
              theme="vs"
              options={options}
              onChange={this.onDataChange.bind(this)}
              value={code}
            />
          </div>
          <div className={style.sync_circle}>
            <Button type="primary" icon="sync" loading={this.state.loading} onClick={this.syncDataArea.bind(this)}>同步模块数据</Button>
          </div>
        </div> : null }

        {
          this.props.templateID < 4
            ? <div>
                <div className={style.text_title}>编辑模块文字</div>
                <TextArea placeholder="正在加载文本信息..."  value={txtData}  rows={8} onChange={this.updateTextarea.bind(this)}/>
                <div className={style.sync_circle}>
                   <Button type="primary" icon="sync" onClick={this.syncTextArea.bind(this)} loading={this.state.loading}>同步模块文字</Button>
                </div>
          </div>
          : null
        }

      </div>
    </div>
  }
}
